<template>
  <div class="app-container">
    <!-- 查询 -->
    <div class="filter-container">
      <el-row :gutter="0">
        <el-form :inline="true" class="search-form">
          <el-form-item label="名称">
            <el-input v-model="query.name" class="filter-item" placeholder="请输入名称" clearable/>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="query.range_date"
              type="daterange"
              class="filter-item"
              style="width: 240px;"
              range-separator="-"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button class="" type="primary" icon="el-icon-search" @click="search">查询</el-button>
            <el-button class="" type="success" icon="el-icon-refresh-right" plain @click="refresh()">刷新</el-button>
          </el-form-item>

          <el-form-item style="float: right">
            <el-button class="" type="primary" @click="add()">添加</el-button>
          </el-form-item>
        </el-form>
      </el-row>
    </div>
    <!-- 列表 -->
    <el-table ref="tableRef" v-loading="loading" :data="datas" :max-height="height" style="width: 100%" border @sort-change="sorting">
      <el-table-column prop="id" label="ID" min-width="60" align="center" sortable="custom"/>
      <el-table-column prop="name" label="名称" min-width="100" align="center"/>
      <el-table-column prop="remark" label="备注" min-width="200" align="center"/>
      <el-table-column prop="sorting" label="排序" min-width="75" align="center" sortable="custom"/>
      <el-table-column prop="status" label="启用" min-width="75" align="center" sortable="custom" fixed="right">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2" @change="isActivate(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" min-width="160" align="center" sortable="custom"/>
      <el-table-column label="操作" min-width="120" align="center" fixed="right">
        <template slot-scope="{ row }">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(row)">编辑</el-button>
          <el-button v-if="row.id != '1'" type="danger" icon="el-icon-delete" size="mini" @click="del(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="query.page" :limit.sync="query.limit" @pagination="list"/>
    <!-- 添加、修改 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" top="10vh" :close-on-click-modal="false" :before-close="cancel">
      <el-form ref="formRef" :rules="rules" :model="model" label-width="100px" class="" :style="{height:height-120+'px'}">
        <el-form-item label="是否启用" prop="status">
          <el-switch v-model="model.status" :active-value="1" :inactive-value="2"></el-switch>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="model.name" placeholder="请输入名称" clearable/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="model.remark" type="textarea" maxlength="120" placeholder="" show-word-limit/>
        </el-form-item>
        <el-form-item label="排序" prop="sorting">
          <el-input-number v-model="model.sorting" :min="1" :max="99999" step-strictly controls-position="right"/>
        </el-form-item>
        <el-form-item label="权限" prop="access_ids" style="width: 50%">
          <el-tree
            ref="menuRef"
            :data="menuTree"
            :default-checked-keys="model.access_ids"
            :props="{children: 'children',label: 'name'}"
            :check-strictly="checkStrictly"
            :expand-on-click-node="false"
            node-key="id"
            :default-expand-all="false"
            show-checkbox
            highlight-current
            @check="menuCheck"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ node.label }}</span>
              <!--<span>
                <el-button v-if="data.children[0]" type="text" size="mini" @click="() => menuChildrenAllCheck(data)">全选</el-button>
                <el-button v-if="data.children[0]" type="text" size="mini" @click="() => menuChildrenAllCheck(data, true)">反选</el-button>
                <i class="el-icon-link" style="margin-left:10px;" :title="data.route"/>
                <i class="el-icon-unlock" style="margin-left:10px;" title="无需权限"/>
                <i class="el-icon-user" style="margin-left:10px;" title="无需登录"/>
              </span>-->
            </span>
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button :loading="btnLoading" type="primary" @click="submit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import screenHeight from '@/utils/screen-height'
import Pagination from '@/components/Pagination'
import {list as menuTree} from '@/api/admin/menu'
import {list, info, save, del, disable} from '@/api/admin/role'

export default {
  name: 'AdminAdminrole',
  components: {Pagination},
  data() {
    const accessValidate = (rule, value, callback) => {
      if (value.length < 2) {
        this.$message({
          message: '请至少选择一个权限',
          type: 'info'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      height: 680,
      loading: false,
      datas: [],
      total: 0,
      query: {
        page: 1,
        limit: 20,
        name: '',
        range_date: []
      },
      dialogVisible: false,
      dialogTitle: '',
      btnLoading: false,
      model: {
        id: '',
        name: '',
        remark: '',
        access: '',
        access_ids: [],
        sorting: 10,
        status: 1
      },
      rules: {
        name: [{required: true, message: '请输入名称', trigger: 'blur'}],
        access_ids: [{type: 'array', required: true, validator: accessValidate, trigger: 'blur'}]
      },
      menuTree: [],
      checkStrictly: false,
    }
  },
  created() {
    this.height = screenHeight()
    this.list()
  },
  methods: {
    // 列表
    list() {
      this.loading = true
      list(this.query).then(res => {
        this.datas = res.data.data
        this.total = res.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 添加
    add() {
      this.dialogVisible = true
      this.dialogTitle = '新增'
      menuTree().then(res => {
        this.menuTree = res.data.data
      })
      this.reset()

      if (this.$refs.menuRef) {
        this.$refs.menuRef.setCheckedNodes([])
      }
    },
    // 修改
    edit(row) {
      this.dialogVisible = true
      this.dialogTitle = '编辑：' + row.id
      menuTree().then(res => {
        this.menuTree = res.data.data
      })
      info({
        id: row.id
      }).then(res => {
        this.reset(res.data)
      })

      this.$nextTick(() => {
        this.$refs.menuRef.setCheckedNodes(this.model.access_ids)
        this.checkStrictly = false
      })
    },
    // 删除
    del(row) {
      this.$confirm(
        '确定要删除ID： <span style="color:red">' + row.id + ' </span> 这条数据吗？',
        'ID：' + row.id,
        {type: 'warning', dangerouslyUseHTMLString: true}
      ).then(() => {
        this.loading = true
        del({
          id: row.id
        }).then(res => {
          this.loading = false
          if (res.status == 1) {
            this.list()
            this.reset()
            this.$message.success(res.msg)
          } else {
            this.$message.info(res.msg)
          }
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
      })
    },
    // 取消
    cancel() {
      this.dialogVisible = false
      this.reset()
    },
    // 提交
    async submit() {
      this.$refs['formRef'].validate(valid => {
        if (valid) {
          this.btnLoading = true
          save(this.model, 'post').then(res => {
            this.btnLoading = false
            this.list()
            this.dialogVisible = false
            this.$message.success(res.msg)
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },
    // 重置
    reset(row) {
      if (row) {
        this.model = row
      } else {
        this.model = this.$options.data().model
      }
      if (this.$refs['formRef'] !== undefined) {
        this.$refs['formRef'].resetFields()
      }
    },
    // 查询
    search() {
      this.query.page = 1
      this.list()
    },
    // 刷新
    refresh() {
      this.query = this.$options.data().query
      this.list()
    },
    // 排序
    sorting(sort) {
      this.query.sort_field = sort.prop
      this.query.sort_value = ''
      if (sort.order === 'ascending') {
        this.query.sort_value = 'asc'
        this.list()
      }
      if (sort.order === 'descending') {
        this.query.sort_value = 'desc'
        this.list()
      }
    },
    // 启用/禁用
    isActivate(row) {
      this.loading = true
      disable({
        id: row.id,
        status: row.status
      }).then(res => {
        this.list()
        this.$message.success(res.msg)
      }).catch(() => {
        this.list()
      })
    },

    // 菜单选择
    menuCheck(data, node) {
      this.model.access_ids = node.checkedKeys
    },
    // 菜单全选反选
    menuChildrenAllCheck(data, back = false) {
      const menu_ids = this.model.access_ids
      const menu_ids_child = []
      menu_ids_child.push(data.id)
      if (data.children) {
        for (let i = 0; i < data.children.length; i++) {
          menu_ids_child.push(data.children[i].id)
        }
      }
      if (back) {
        for (let i = 0; i < menu_ids.length; i++) {
          for (let j = 0; j < menu_ids_child.length; j++) {
            if (menu_ids[i] === menu_ids_child[j]) {
              menu_ids.splice(i, 1)
            }
          }
        }
        this.model.access_ids = menu_ids
        this.$refs.menuRef.setCheckedKeys(menu_ids)
      } else {
        const menu_ids_temp = []
        const menu_ids_all = menu_ids.concat(menu_ids_child)
        for (let i = 0; i < menu_ids_all.length; i++) {
          if (menu_ids_temp.indexOf(menu_ids_all[i]) === -1) {
            menu_ids_temp.push(menu_ids_all[i])
          }
        }
        this.model.access_ids = menu_ids_temp
        this.$refs.menuRef.setCheckedKeys(menu_ids_temp)
      }
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: center;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
